package com.jieao.template.config;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * es 配置
 *
 * @author Jzw
 * @since 2020/7/20 10:16
 */
@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class EsConfig
{
    private String host;

    private Integer port;

    private String schema = "http";

    /**
     * 设置连接超时时间
     */
    private int connectTimeOut = 2000;

    private int socketTimeOut = 30000;

    private int connectionRequestTimeOut = 10000;


    /**
     * 一次最多接收请求
     */
    private int maxConnectNum = 100;


    /**
     * 某一个服务每次能并行接收的请求数量
     */
    private int maxConnectPerRoute = 10;

    private boolean uniqueConnectTimeConfig = true;

    private boolean uniqueConnectNumConfig = true;

    private HttpHost httpHost;

    private RestClientBuilder builder;

    private RestHighLevelClient client;

    /**
     * 初始化连接
     *
     * @return
     */
    @Bean(destroyMethod = "close")
    public RestHighLevelClient restHighLevelClient()
    {
        httpHost = new HttpHost(host, port, schema);
        builder = RestClient.builder(httpHost);
        // 设置连接时间
        if (uniqueConnectTimeConfig)
        {
            setConnectTimeOutConfig();
        }
        // 设置连接数
        if (uniqueConnectNumConfig)
        {
            setMultiConnectConfig();
        }

        client = new RestHighLevelClient(builder);
        return client;
    }

    /**
     * 异步httpclient的连接延迟配置
     * 设置修改默认请求配置的回调（例如：请求超时，认证，或者其他设置
     */
    public void setConnectTimeOutConfig()
    {
        builder.setRequestConfigCallback(builder -> {
            builder.setConnectTimeout(connectTimeOut);
            builder.setSocketTimeout(socketTimeOut);
            builder.setConnectionRequestTimeout(connectionRequestTimeOut);
            return builder;
        });
    }

    /**
     * 线程设置
     */
    public void setMultiConnectConfig()
    {
        builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> {
            httpAsyncClientBuilder.setMaxConnTotal(maxConnectNum);
            httpAsyncClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
            return httpAsyncClientBuilder;
        });
    }

}
